package utilidades;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

public class GenerarQR {

    private static final String FORMATO_IMAGEN = "jpeg";
    private static final String RUTA_IMAGEN = "codigo.JPEG";
    private static final int ancho = 500;
    private static final int alto = 500;
    private static final String datos = "clave generada aleatoriamente";

    public static void main(String args[]) throws FileNotFoundException, IOException {
        BitMatrix bm = null;

        try {

            Writer writer = new QRCodeWriter();
            bm = writer.encode(datos, BarcodeFormat.QR_CODE, ancho, alto);
        } catch (WriterException ex) {
            System.out.println("Error al escribir");
        }

        BufferedImage imagen = new BufferedImage(ancho, alto, BufferedImage.TYPE_INT_RGB);
       
        //Genera el código creando una matriz.
        for (int y = 0; y < ancho; y++) {
            for (int x = 0; x < alto; x++) {
                int grayValue = (bm.get(x, y) ? 1 : 0) & 0xff;
                imagen.setRGB(x, y, (grayValue == 0 ? 0 : 0xFFFFFF));
            }
        }

        imagen = invertirColores(imagen);
        FileOutputStream qrCode = new FileOutputStream(RUTA_IMAGEN);
        ImageIO.write(imagen, FORMATO_IMAGEN, qrCode);
        qrCode.close();
        Desktop d = Desktop.getDesktop();
        d.open(new File(RUTA_IMAGEN));

    }

    private static BufferedImage invertirColores(BufferedImage imagen) {
        for (int x = 0; x < ancho; x++) {
            for (int y = 0; y < alto; y++) {
                int rgb = imagen.getRGB(x, y);
                if (rgb == -16777216) {
                    imagen.setRGB(x, y, -1);
                } else {
                    imagen.setRGB(x, y, -16777216);
                }
            }
        }
        return imagen;
    }
}
